package com.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.activity.bean.UserBean;
import com.activity.fragment.BaseListViewFragment;
import com.activity.fragment.OpusFragment;
import com.api.param.UpdateUserParam;
import com.api.viewModel.LoginVM;
import com.baoyz.actionsheet.ActionSheet;
import com.example.apple.ddhr_new.R;
import com.example.apple.ddhr_new.adapter.BaseFragmentAdapter;

import com.example.apple.ddhr_new.utils.ActivityUtil;
import com.example.apple.ddhr_new.utils.ImageViewUtil;
import com.example.apple.ddhr_new.utils.ScreenUtil;
import com.example.lzbase.BaseViewModelActivity;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.gyf.barlibrary.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import event.MessageEvent;

public class PersonalActivity extends BaseViewModelActivity<LoginVM> implements AppBarLayout.OnOffsetChangedListener {


    @BindView(R.id.app_bar)
    AppBarLayout appBar;
    @BindView(R.id.magic_indicator)
    MagicIndicator magicIndicator;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.toolbar)


    Toolbar toolbar;


    @BindView(R.id.bg_img)
    View bgImg;
    @BindView(R.id.nav_back)
    ImageButton navBack;
    @BindView(R.id.nav_title)
    TextView navTitle;
    @BindView(R.id.title_layout)
    RelativeLayout titleLayout;
    @BindView(R.id.l_bg)
    LinearLayout lBg;
    @BindView(R.id.btn_detail)
    ImageButton btnDetail;
    @BindView(R.id.nav_right)
    ImageButton navRight;
    @BindView(R.id.nav_title_right)
    TextView navTitleRight;
    @BindView(R.id.l_icon)
    LinearLayout lIcon;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_core)
    TextView tvCore;
    @BindView(R.id.tv_fans)
    TextView tvFans;
    @BindView(R.id.tv_brief)
    TextView tvBrief;
    @BindView(R.id.iv_icon)
    ImageView ivIcon;
    @BindView(R.id.iv_vip)
    ImageView ivVip;

    private BaseFragmentAdapter adapter;
    private String[] mTitleDataList = {
            "作品集", "店铺", "自媒体"
    };
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private NoScrollBehavior myAppBarLayoutBehavoir;
    private String imgurl;

    @Override
    protected int titleText() {
        return R.string.gerenzhuye;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_personal2;
    }

    @Override
    public void initStatusBar() {
        ImmersionBar.with(this)
                .transparentStatusBar()
                .init();
    }


    @Override
    protected void created(@Nullable Bundle savedInstanceState) {

        super.created(savedInstanceState);
        setImageRight(R.drawable.bianji_white);
        super.created(savedInstanceState);
        fragments.add(new OpusFragment());
        fragments.add(new OpusFragment());
        fragments.add(new OpusFragment());
        adapter = new BaseFragmentAdapter(getSupportFragmentManager(), fragments);
        viewPager.setAdapter(adapter);

        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdjustMode(true);
//        commonNavigator.setLeftPadding(ScreenUtil.dp2px(this,10));

        commonNavigator.setAdapter(new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return mTitleDataList.length;
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                ColorTransitionPagerTitleView colorTransitionPagerTitleView = new ColorTransitionPagerTitleView(context);
                colorTransitionPagerTitleView.setNormalColor(getResources().getColor(R.color.color_cell_title));
                colorTransitionPagerTitleView.setSelectedColor(getResources().getColor(R.color.color_orange));
                colorTransitionPagerTitleView.setText(mTitleDataList[index]);
                colorTransitionPagerTitleView.setTextSize(16);

                colorTransitionPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        viewPager.setCurrentItem(index);
                    }
                });
                return colorTransitionPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_WRAP_CONTENT);
                indicator.setColors(getResources().getColor(R.color.color_orange));
                return indicator;
            }
        });
        magicIndicator.setNavigator(commonNavigator);

        ViewPagerHelper.bind(magicIndicator, viewPager);


//        //防止toolbar顶入状态栏
//        CollapsingToolbarLayout.LayoutParams lp2 = (CollapsingToolbarLayout.LayoutParams) toolbar.getLayoutParams();
//        lp2.topMargin = ImmersionBar.getStatusBarHeight(this);
//        toolbar.setLayoutParams(lp2);
        CollapsingToolbarLayout.LayoutParams lp2 = (CollapsingToolbarLayout.LayoutParams) toolbar.getLayoutParams();
        lp2.topMargin = ImmersionBar.getStatusBarHeight(this);
        toolbar.setLayoutParams(lp2);

//        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) lBg.getLayoutParams();
//        params.setMargins(0,ImmersionBar.getStatusBarHeight(this)+ScreenUtil.dp2px(this,44),0,0);
        myAppBarLayoutBehavoir = (NoScrollBehavior)
                ((CoordinatorLayout.LayoutParams) appBar.getLayoutParams()).getBehavior();

        appBar.addOnOffsetChangedListener(this);

        toolbar.setBackgroundColor(getResources().getColor(R.color.transparent));


        viewModel.updateUserinfo.observe(this,res->{


            updateUser();
        });
        updateUser();



    }

    private void updateUser() {
        UserBean userBean = App.getInstance().getAccount();

        ImageViewUtil.loadCircleImage(userBean.getUsericon(), ivIcon, this);
        tvName.setText(userBean.getUsernickname() + "  " + userBean.getUserrank());
        tvCore.setText("关注 " + userBean.getUserfocusnum());
        tvFans.setText("粉丝 " + "0");
        tvBrief.setText(userBean.getUserbrief());

        if(userBean.getUsercertificated().equals("1")){
            ivVip.setVisibility(View.VISIBLE);
        }else
        {
            ivVip.setVisibility(View.GONE);
        }
    }


    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        //顶部渐变 标题栏处理
        float percent = Float.valueOf(Math.abs(verticalOffset)) / Float.valueOf(appBarLayout.getTotalScrollRange());
        int alpha = (int) (255 * percent);
        titleLayout.setBackgroundColor(Color.argb(alpha, 236, 117, 51));
//        titleLayout.setAlpha(alpha);

        navTitle.setAlpha(percent);
        lBg.setBackgroundColor(Color.argb(alpha, 236, 117, 51));
        lBg.findViewById(R.id.l_icon).setAlpha(1 - percent);
        bgImg.setBackgroundColor(Color.argb(alpha, 236, 117, 51));
//        if (percent < 0.5) {
//            navBack.setImageResource(R.mipmap.houtui);
//        } else {
//            navBack.setBackground(null);
//        }


        //滑动事件处理
        if (percent == 0) {
            //当完全展开时  appbar可滑动  禁止refresh(可根据需求不禁止刷新)
            myAppBarLayoutBehavoir.setNoScroll(false);
            ((BaseListViewFragment) fragments.get(viewPager.getCurrentItem())).getRefreshLayout().setEnableRefresh(true);

        } else if (percent == 1) {
            //当完全折叠时  appbar不可滑动使tab吸顶   允许refresh
            ((BaseListViewFragment) fragments.get(viewPager.getCurrentItem())).getRefreshLayout().setEnableRefresh(false);
            myAppBarLayoutBehavoir.setNoScroll(false);
        } else {
            //滑动中 appbar可滑动 禁止refresh(建议禁止刷新,否则会appbar影响滑动流畅)
            myAppBarLayoutBehavoir.setNoScroll(false);
            ((BaseListViewFragment) fragments.get(viewPager.getCurrentItem())).getRefreshLayout().setEnableRefresh(false);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        appBar.removeOnOffsetChangedListener(this);
    }


    @OnClick(R.id.btn_detail)
    public void onClick() {
        btnDetail.setSelected(!btnDetail.isSelected());
        if(btnDetail.isSelected()){
            tvBrief.setLines(3);
        }else {
            tvBrief.setLines(1);
        }
    }


    @OnClick(R.id.l_icon)
    public void onViewClicked() {
        ActionSheet.createBuilder(PersonalActivity.this, getSupportFragmentManager())
                .setCancelButtonTitle(getString(R.string.cacel))
                .setOtherButtonTitles(getString(R.string.camera), getString(R.string.take_photo))
                .setCancelableOnTouchOutside(true)
                .setListener(new ActionSheet.ActionSheetListener() {
                    @Override
                    public void onDismiss(ActionSheet actionSheet, boolean isCancel) {

                    }

                    @Override
                    public void onOtherButtonClick(ActionSheet actionSheet, int index) {

                        if (index == 0) {
                            PictureSelector.create(PersonalActivity.this)
                                    .openCamera(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()

                                    .maxSelectNum(1)// 最大图片选择数量 int
                                    .imageSpanCount(4)// 每行显示个数 int
                                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                                    .previewImage(true)// 是否可预览图片 true or false
                                    .previewVideo(true)// 是否可预览视频 true or false
                                    .enablePreviewAudio(true) // 是否可播放音频 true or false
                                    .isCamera(true)// 是否显示拍照按钮 true or false
                                    .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                                    .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                                    .enableCrop(false)// 是否裁剪 true or false
                                    .compress(true)// 是否压缩 true or false
                                    .isGif(false)// 是否显示gif图片 true or false
                                    .openClickSound(false)// 是否开启点击声音 true or false
                                    .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                        } else {
                            PictureSelector.create(PersonalActivity.this)
                                    .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()

                                    .maxSelectNum(1)// 最大图片选择数量 int
                                    .imageSpanCount(4)// 每行显示个数 int
                                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                                    .previewImage(true)// 是否可预览图片 true or false
                                    .previewVideo(true)// 是否可预览视频 true or false
                                    .enablePreviewAudio(true) // 是否可播放音频 true or false
                                    .isCamera(true)// 是否显示拍照按钮 true or false
                                    .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                                    .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                                    .enableCrop(false)// 是否裁剪 true or false
                                    .compress(true)// 是否压缩 true or false
                                    .isGif(false)// 是否显示gif图片 true or false
                                    .openClickSound(false)// 是否开启点击声音 true or false
                                    .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                        }
                    }
                }).show();
    }

    @Override
    protected void titleRightClick() {
        ActivityUtil.startActivity(this, OpusPostActivity.class);
    }


    @OnClick(R.id.tv_name)
    public void nameClicked() {
        ActivityUtil.startActivity(this, PersonInfoActivity.class);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);


                    ArrayList<String> arrayList = new ArrayList<>();
                    for (int i = 0; i < selectList.size(); i++) {
                        LocalMedia media = selectList.get(i);
                        String path = media.getCompressPath();

                        arrayList.add(path);

                    }

                    viewModel.uplaodImages(arrayList, new LoginVM.ImageResult() {
                        @Override
                        public void result(ArrayList<String> result,ArrayList<String> origin) {

                            if(result.size()==0)
                                return;
                            imgurl = result.get(0);

                            UpdateUserParam param = new UpdateUserParam();
                            UserBean userBean = App.getInstance().getAccount();
                            param.usericon =imgurl;
                            param.userrank=userBean.getUserrank();
                            param.usernickname  =userBean.getUsernickname();
                            param.userbirthday  =userBean.getUserbirthday();
                            param.userprovince  =userBean.getUserprovince();
                            param.userrealname = userBean.getUserrealname();
                            param.usercity  =userBean.getUsercity();
                            param.usersex  =userBean.getUsersex();
                            param.userbrief  =userBean.getUserbrief();
                            param.userfacecertificated = userBean.getUserfacecertificated();
                            param.userbackground  =userBean.getUserbackground();
                            param.useremail = userBean.getUseremail();
                            param.useraddress = userBean.getUseraddress();
                            param.usercompany = userBean.getUsercompany();
                            param.usertel = userBean.getUsertel();
                            addSubscription(viewModel.updateUserinfo(param));
                        }
                    },"usericon");
//                    picture.reload();

                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的

                    break;
            }
        }
    }

    @Override
    public void onMessageEvent(MessageEvent event) {
        super.onMessageEvent(event);
        if(event.getMessage() == MessageEvent.MESSAGE_EVENT_UPDATE_USER){


            updateUser();


        }
    }



}
